package com.xt.base.acegi;

import org.acegisecurity.Authentication;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.ui.WebAuthenticationDetails;
import org.acegisecurity.userdetails.UserDetails;

public class AcegiUtils {

	public static String getUsername() {
		SecurityContext ctx = SecurityContextHolder.getContext();
		if (ctx != null) {
			Authentication auth = ctx.getAuthentication();
			if (auth != null) {
				Object principal = auth.getPrincipal();
				if (principal instanceof UserDetails) {
					return ((UserDetails) principal).getUsername();
				} else {
					return principal.toString();
				}
			}
		}
		return null;
	}

	public static String getPassword() {
		SecurityContext ctx = SecurityContextHolder.getContext();
		if (ctx != null) {
			Authentication auth = ctx.getAuthentication();
			if (auth != null) {
				Object principal = auth.getPrincipal();
				if (principal instanceof UserDetails) {
					return ((UserDetails) principal).getPassword();
				} else {
					return null;
				}
			}

		}
		return null;
	}

	public static String getSessionID() {
		SecurityContext ctx = SecurityContextHolder.getContext();
		if (ctx != null) {
			if (ctx instanceof SecurityContext) {
				SecurityContext sc = (SecurityContext) ctx;
				Authentication auth = sc.getAuthentication();
				if (auth != null) {
					Object details = auth.getDetails();
					if (details instanceof WebAuthenticationDetails) {
						return ((WebAuthenticationDetails) details)
								.getSessionId();
					} else {
						return null;
					}
				}
			}
		}
		return null;
	}

}
